import { USER_MENU } from '@/constant'
import { defineStore } from 'pinia'
// import { ElLoading } from 'element-plus'

export const useMenuStore = defineStore('menus', {
  state: () => ({
    menus: JSON.parse(localStorage.getItem(USER_MENU) || '[]') || [],
  }),
  actions: {
    setMenus(data: any) {
      this.menus = data
    },
    setAutherMenus(data: any) {
      this.menus = []
      data.forEach((menu: any) => {
        if (menu.components == '#') {
          const menuData = {
            path: `/${menu.path}`,
            name: menu.path,
            meta: {
              title: menu.name,
              icon: menu.icon,
              type: '0',
            },
            children: [],
          }

          addMenuData(menuData.children, menu.children, menuData.path)

          this.menus = [...this.menus, menuData]
        }

        localStorage.setItem(USER_MENU, JSON.stringify(this.menus))
      })
      // {
      //   path: '/permission',
      //   name: 'permission',
      //   meta: {
      //     title: '权限管理',
      //     icon: 'Lock',
      //     type: '0',
      //   },
      //   children: [
      //     {
      //       path: '/permission/users',
      //       name: '/permission/users',
      //       meta: {
      //         title: '用户管理',
      //         icon: 'User',
      //         type: '0',
      //       },
      //       children: [],
      //     },
      //     {
    },
  },
})

const addMenuData = (menuDataChildren: any, children: any, fatherPath: any) => {
  if (children && children.length) {
    children.forEach((menu: any) => {
      const path = `${fatherPath}/${menu.path}`
      const childrenRoot: any = {
        path,
        name: path,
        meta: {
          title: menu.name,
          icon: menu.icon,
          type: menu.type,
          components: menu.components,
        },
        children: [],
      }

      menuDataChildren.push(childrenRoot)

      addMenuData(childrenRoot.children, menu.children, path)
    })
  }
}
